<?php


namespace app\api\service;

use app\common\model\Config;
use Endroid\QrCode\QrCode;
use think\App;
use think\Env;
use think\Exception;
use Yansongda\Pay\Pay;

/**
 * 根据url爬去文章
 * Class FetchArticleService
 * @package app\api\service
 */
class FetchArticleService
{
    /**
     *
     * 根据url爬去文章
     * @param $target_url 需要抓取正文的文章链接
     * @param string $contentwithhtml 返回的文章是否包含 HTML 标签 'true':是,'false':否
     * @param string $htmlsourcecontent 是否返回文章页面原始 HTML 内容，供您二次解析或分析正文失败时使用，需要注意接口的性能问题 'true':是,'false':否
     */
    public function fetchArticle($target_url,$contentwithhtml = 'true',$htmlsourcecontent='false')
    {
        //手册地址:https://www.gugudata.com/api/details/fetchcontent
        $appkey = Config::where('group','fetch_article_config')
            ->where('name','appkey')
            ->value('value');//appkey
        $contentwithhtml = 'true';//返回的文章是否包含 HTML 标签
        $htmlsourcecontent = 'false';//是否返回文章页面原始 HTML 内容，供您二次解析或分析正文失败时使用，需要注意接口的性能问题

        $res = [
            'code' => 200,
            'msg' => 'success',
            'title'=>'',
            'html_content'=>'',
        ];

        try {
            $postData = [
                'appkey' => $appkey,
                'url' => $target_url,
                'contentwithhtml' => $contentwithhtml,
                'htmlsourcecontent' => $htmlsourcecontent,
            ];

            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => "https://api.gugudata.com/news/fetchcontent",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => http_build_query($postData),
                CURLOPT_HTTPHEADER => [
                    "Content-Type: application/x-www-form-urlencoded"
                ],
            ]);

            $response = curl_exec($curl);
            curl_close($curl);

            $resData = json_decode($response, true);
            $status_code = $resData['DataStatus']['StatusCode'] ?? null;
            if ($status_code != 100){
                $res['code'] = 500;
                $res['msg'] = $resData['DataStatus']['StatusDescription'] ?? '调用Api请求失败';
            }else{
                $res['title'] = $resData['Data']['Title'];
                $res['html_content'] = str_replace(array("\t", "\r", "\n"), '', $resData['Data']['Content']);
                if (empty($res['html_content'])){
                    $res['code']= 500;
                    $res['msg']= '该文章无法抓取';
                }
            }
        }catch (Exception $exception){
            $res['code']= 500;
            $res['msg']= '系统错误:' . $exception->getMessage() . $exception->getLine();
        }
        return $res;
    }
}